'''# built_in'''
import os
import time
import logging
from logging.handlers import RotatingFileHandler

'''# custom'''
from common import GSDSTORE


class Stats:

    def __init__(self) -> None:
        self.start_time = None
        self.end_time = None

    def testTime_start(self):
        self.start_time = time.time()

    def testTime_end(self):
        self.end_time = time.time()


class TextLogger(object):

    def __repr__(self) -> str:
        return "文本日志记录器"
    
    def __init__(self) -> None:
        return
    
    def test_start(self):
        stats.testTime_start()
        startTime = time.strftime('%Y/%m/%d %H:%M:%S', time.localtime(stats.start_time))
        logger.info(f"\n\n  ========= 测试开始 : {startTime} =========\n")

    def test_end(self, collect):
        formJson = {'total': 0, 'implement': 0, 'passNum': 0, 'failNum': 0, 'abnormalNum': 0}
        for item in collect:
            formJson['total'] += item['total']
            formJson['implement'] += item['implement']
            formJson['passNum'] += item['passNum']
            formJson['failNum'] += item['failNum']
            formJson['abnormalNum'] += item['abnormalNum']
        stats.testTime_end()
        endTime = time.strftime('%Y/%m/%d %H:%M:%S', time.localtime(stats.end_time))
        logger.info(f"\n\n  ========= 测试结束 : {endTime} =========\n")
        logger.info(f"\n  总耗时  : {stats.end_time - stats.start_time:.3f} 秒\n")
        logger.info(f"\n  预备执行用例数量 : {formJson['total']}")
        logger.info(f"\n  实际执行用例数量 : {formJson['implement']}")
        logger.info(f"\n  通过 : {formJson['passNum']}")
        logger.info(f"\n  失败 : {formJson['failNum']}")
        logger.info(f"\n  异常 : {formJson['abnormalNum']}")

    def info(self, msg):
        logger.info(msg)

    def debug(self, msg):
        logger.debug(msg)
    
    def exceptinfo(self, msg):
        logger.exception(msg)


logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logFile = os.path.join(f"{GSDSTORE['WORKPATH']['ROOT']}\\result\\log",'testresult.log')
handler = RotatingFileHandler(logFile, maxBytes=1024*1024*30, backupCount=3, encoding='utf8')
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter(fmt="%(message)s")
handler.setFormatter(formatter)
handler.doRollover()
logger.addHandler(handler)  # 加载handlers对象
stats = Stats()
from utils.log.trusteeship import trusteeship
trusteeship.register([stats, TextLogger()])